<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
                        <el-form-item label="订单编号" prop="orderNum">
                            <el-input
                                    v-model="queryParams.orderNum"
                                    placeholder="请输入订单编号"
                                    clearable
                                    @keyup.enter.native="handleQuery"
                            />
                        </el-form-item>
                        <el-form-item label="用户id" prop="userId">
                            <el-input
                                    v-model="queryParams.userId"
                                    placeholder="请输入用户id"
                                    clearable
                                    @keyup.enter.native="handleQuery"
                            />
                        </el-form-item>
                        <el-form-item label="司机id" prop="driverId">
                            <el-input
                                    v-model="queryParams.driverId"
                                    placeholder="请输入司机id"
                                    clearable
                                    @keyup.enter.native="handleQuery"
                            />
                        </el-form-item>
                        <el-form-item label="出行类型id -快车/专车" prop="tripTypeId">
                            <el-input
                                    v-model="queryParams.tripTypeId"
                                    placeholder="请输入出行类型id -快车/专车"
                                    clearable
                                    @keyup.enter.native="handleQuery"
                            />
                        </el-form-item>
                        <el-form-item label="优惠卷id" prop="couponId">
                            <el-input
                                    v-model="queryParams.couponId"
                                    placeholder="请输入优惠卷id"
                                    clearable
                                    @keyup.enter.native="handleQuery"
                            />
                        </el-form-item>
                        <el-form-item label="小费金额" prop="tipNumber">
                            <el-input
                                    v-model="queryParams.tipNumber"
                                    placeholder="请输入小费金额"
                                    clearable
                                    @keyup.enter.native="handleQuery"
                            />
                        </el-form-item>
                        <el-form-item label="订单信息id" prop="orderInfoId">
                            <el-input
                                    v-model="queryParams.orderInfoId"
                                    placeholder="请输入订单信息id"
                                    clearable
                                    @keyup.enter.native="handleQuery"
                            />
                        </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                        type="primary"
                        plain
                        icon="el-icon-plus"
                        size="mini"
                        @click="handleAdd"
                        v-hasPermi="['order:order:add']"
                >新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="success"
                        plain
                        icon="el-icon-edit"
                        size="mini"
                        :disabled="single"
                        @click="handleUpdate"
                        v-hasPermi="['order:order:edit']"
                >修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="danger"
                        plain
                        icon="el-icon-delete"
                        size="mini"
                        :disabled="multiple"
                        @click="handleDelete"
                        v-hasPermi="['order:order:remove']"
                >删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="info"
                        plain
                        icon="el-icon-upload2"
                        size="mini"
                        @click="handleImport"
                        v-hasPermi="['order:order:import']"
                >导入</el-button>
            </el-col>

            <el-col :span="1.5">
                <el-button
                        type="warning"
                        plain
                        icon="el-icon-download"
                        size="mini"
                        @click="handleExport"
                        v-hasPermi="['order:order:export']"
                >导出</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
                    <el-table-column label="订单id" align="center" prop="orderId" />
                    <el-table-column label="订单编号" align="center" prop="orderNum" />
                    <el-table-column label="用户id" align="center" prop="userId" />
                    <el-table-column label="司机id" align="center" prop="driverId" />
                    <el-table-column label="出行类型" align="center">
                    <template slot-scope="scope">
                        {{ scope.row.tripTypeId === 1 ? '快车' : (scope.row.tripTypeId === 2 ? '专车' : '未知类型') }}
                    </template>
                    </el-table-column>                    
                    <el-table-column label="订单类型 -实时单/预约" align="center" prop="orderType" />
                    <el-table-column label="优惠卷id" align="center" prop="couponId" />
                    <el-table-column label="小费金额" align="center" prop="tipNumber" />
                    <el-table-column label="订单信息id" align="center" prop="orderInfoId" />
                    <el-table-column label="状态" align="center">
                        <template slot-scope="scope">
                            {{ scope.row.status == 1 ? '待接单（Pending）' :
                            scope.row.status == 2 ? '已接受（Accepted）' :
                            scope.row.status == 3 ? '行驶中（In Progress）' :
                            scope.row.status == 4 ? '已完成（Completed）' :
                            scope.row.status == 5 ? '取消（Cancelled by Passenger）' :
                            scope.row.status == 6 ? '拒绝（Cancelled by Driver）' :
                            scope.row.status == 7 ? '超时未响应（Timed Out）' :
                            scope.row.status == 8 ? '特殊情况（Special Cases）' :
                            scope.row.status == 9 ? '待付款（Obligations）' : 
                            '未知状态' }}
                        </template>
                    </el-table-column>                   
                     <el-table-column label="备注" align="center" prop="remark" />
                    <el-table-column label="查看订单评价" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-view"
                        @click="handleViewReview(scope.row)"
                    >
                        查看评价
                    </el-button>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-edit"
                            @click="handleUpdate(scope.row)"
                            v-hasPermi="['order:order:edit']"
                    >修改</el-button>
                    <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-delete"
                            @click="handleDelete(scope.row)"
                            v-hasPermi="['order:order:remove']"
                    >删除</el-button>
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-location"
                        @click="handleViewRouteLocations(scope.row)"
                    >查看途径地点</el-button>

                </template>
            </el-table-column>
        </el-table>

        <pagination
                v-show="total>0"
                :total="total"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="getList"
        />

        <!-- 添加或修改订单管理对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                                <el-form-item label="订单编号" prop="orderNum">
                                    <el-input v-model="form.orderNum" placeholder="请输入订单编号" />
                                </el-form-item>
                                <el-form-item label="用户id" prop="userId">
                                    <el-input v-model="form.userId" placeholder="请输入用户id" />
                                </el-form-item>
                                <el-form-item label="司机id" prop="driverId">
                                    <el-input v-model="form.driverId" placeholder="请输入司机id" />
                                </el-form-item>
                                <el-form-item label="出行类型id -快车/专车" prop="tripTypeId">
                                    <el-input v-model="form.tripTypeId" placeholder="请输入出行类型id -快车/专车" />
                                </el-form-item>
                                <el-form-item label="优惠卷id" prop="couponId">
                                    <el-input v-model="form.couponId" placeholder="请输入优惠卷id" />
                                </el-form-item>
                                <el-form-item label="小费金额" prop="tipNumber">
                                    <el-input v-model="form.tipNumber" placeholder="请输入小费金额" />
                                </el-form-item>
                                <el-form-item label="订单信息id" prop="orderInfoId">
                                    <el-input v-model="form.orderInfoId" placeholder="请输入订单信息id" />
                                </el-form-item>
                                <el-form-item label="删除标志" prop="delFlag">
                                    <el-input v-model="form.delFlag" placeholder="请输入删除标志" />
                                </el-form-item>
                                <el-form-item label="备注" prop="remark">
                                    <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
                                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
        <!-- 查看订单评价对话框 -->
        <el-dialog
    title="订单评价"
    :visible.sync="reviewDialogVisible"
    width="50%"
    @close="currentReview = null"
>
    <div v-for="item in currentReview">
        <p><strong>评价内容:</strong> {{ item.content }}</p>
        <p><strong>评分:</strong> {{ item.rating }}</p>
    </div>

    <span slot="footer" class="dialog-footer">
        <el-button @click="reviewDialogVisible = false">关闭</el-button>
    </span>
</el-dialog>

<el-dialog
    title="途径地点"
    :visible.sync="routeLocationsDialogVisible"
    width="80%"
    @open="initMap"
    @close="currentRouteLocations = []"
>
    <div id="mapContainer" style="width: 100%; height: 400px;"></div>
    <span slot="footer" class="dialog-footer">
        <el-button @click="routeLocationsDialogVisible = false">关闭</el-button>
        <el-button @click="startAnimation">开始动画</el-button>
        <el-button @click="pauseAnimation">暂停动画</el-button>
        <el-button @click="resumeAnimation">继续动画</el-button>
        <el-button @click="stopAnimation">停止动画</el-button>
    </span>
</el-dialog>


        <!-- 导入对话框 -->
        <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
            <el-upload
                    ref="upload"
                    :limit="1"
                    accept=".xlsx, .xls"
                    :headers="upload.headers"
                    :action="upload.url + '?updateSupport=' + upload.updateSupport"
                    :disabled="upload.isUploading"
                    :on-progress="handleFileUploadProgress"
                    :on-success="handleFileSuccess"
                    :auto-upload="false"
                    drag
            >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip text-center" slot="tip">
                    <!--          <div class="el-upload__tip" slot="tip">
                                <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
                              </div>-->
                    <span>仅允许导入xls、xlsx格式文件。</span>
                    <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
                </div>
            </el-upload>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitFileForm">确 定</el-button>
                <el-button @click="upload.open = false">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import { listOrder, getOrder, delOrder, addOrder, updateOrder ,getOrderReview,getOrderRouteLocations} from "@/api/order/order";
    import { getToken } from '@/utils/auth'
    import request from '@/utils/request'
    import AMapLoader from '@amap/amap-jsapi-loader';
     window._AMapSecurityConfig = {
    // securityJsCode: '324f0a2f4189b61ca893756ec8cb784a'  //你的安全密钥
}
    export default {
        name: "Order",
        data() {
            return {
                map : null,
                routeLocationsDialogVisible: false, // 控制途径地点弹窗的显示
                currentRouteLocations: [], // 存储途径地点的数据
                polyline:null,
                marker:null,
                reviewDialogVisible: false,
                currentReview: null,
                // 遮罩层
                loading: true,
                // 选中数组
                ids: [],
                // 非单个禁用
                single: true,
                // 非多个禁用
                multiple: true,
                // 显示搜索条件
                showSearch: true,
                // 总条数
                total: 0,
                // 订单管理表格数据
                    orderList: [],
                // 弹出层标题
                title: "",
                // 是否显示弹出层
                open: false,
                // 查询参数
                queryParams: {
                    pageNum: 1,
                    pageSize: 10,
                    orderNum: null,
                    userId: null,
                    driverId: null,
                    tripTypeId: null,
                    orderType: null,
                    couponId: null,
                    tipNumber: null,
                    orderInfoId: null,
                    status: null,
                    currentReview:null,
                    reviewDialogVisible: false,

        },
            // 表单参数
            form: {},
            // 导入参数
            upload: {
                // 是否显示弹出层
                open: false,
                        // 弹出层标题
                        title: "",
                        // 是否禁用上传
                        isUploading: false,
                        // 是否更新已经存在的用户数据
                        updateSupport: 0,
                        // 设置上传的请求头部
                        headers: { Authorization: "Bearer " + getToken() },
                // 上传的地址
                url: process.env.VUE_APP_BASE_API + "/order/order/importData"
            },
            // 表单校验
            rules: {
            }
        };
        },
        mounted(){
                    this.$nextTick(() => {
                this.initMap();  // 确保在 DOM 完全加载后初始化地图
            });       //DOM初始化完成进行地图初始化

        },

        created() {
            this.getList();
        },
        methods: {

            async handleViewRouteLocations(row) {
    try {
        const response = await getOrderRouteLocations(row.orderId);
        if (response.code === 200) {
            this.currentRouteLocations = response.data;
            console.log(this.currentRouteLocations);
            this.routeLocationsDialogVisible = true;
            this.initMap();
        } else {
            this.$message.error('获取途径地点信息失败: ' + response.msg);
        }
    } catch (error) {
        this.$message.error('获取途径地点信息失败');
    }
},

initMap() {
    if (this.map) return;
    AMapLoader.reset(),
    AMapLoader.load({
        key: '202824ead4625ceaf1fdb25d42f9fe40',
        version: '2.0',
        plugins: ['AMap.ToolBar', 'AMap.MoveAnimation']
    }).then((AMap) => {
        this.map = new AMap.Map('mapContainer', {
            zoom: 17,
            center: [116.397428, 39.90923],
            mapStyle: 'amap://styles/whitesmoke'
        });

        this.map.addControl(new AMap.ToolBar());

        if (this.currentRouteLocations) {
            this.displayRoute(this.currentRouteLocations);
        }
    }).catch(e => {
        console.error('AMapLoader 加载失败:', e);
    });
},

displayRoute(routeData) {
    if (this.map && routeData.length > 0) {
        const path = routeData.map(point => [
            parseFloat(point.positionLongitude), 
            parseFloat(point.positionLatitude)
        ]);

        if (this.polyline) {
            this.map.remove(this.polyline); // 删除之前的路径
        }

        this.polyline = new AMap.Polyline({
            path: path,
            strokeColor: "#28F",
            strokeWeight: 6,
            lineJoin: 'round'
        });
        this.map.add(this.polyline);
        this.map.setFitView(this.polyline);

        if (this.marker) {
            this.map.remove(this.marker); // 删除之前的标记
        }

        this.marker = new AMap.Marker({
            map: this.map,
            position: path[0],
            icon: "https://webapi.amap.com/images/car.png",
            offset: new AMap.Pixel(-26, -13),
            autoRotation: true
        });
    }
},

startAnimation() {
    if (this.marker && this.polyline) {
        this.marker.moveAlong(this.polyline.getPath(), {
            duration: 5000,
            autoRotation: true
        });
    } else {
        console.warn('marker 或 polyline 尚未初始化');
    }
},

pauseAnimation() {
    if (this.marker) {
        this.marker.pauseMove();
    }
},

resumeAnimation() {
    if (this.marker) {
        this.marker.resumeMove();
    }
},

stopAnimation() {
    if (this.marker) {
        this.marker.stopMove();
    }
},

            async handleViewReview(row) {
            try {
                const response = await getOrderReview(row.orderId);  // 调用封装的接口方法
                if (response.code === 200) {
                    this.currentReview = response.data;
                    console.log('Current Review:', this.currentReview);
                    this.reviewDialogVisible = true;  // 打开弹窗

                } else {
                    this.$message.error('获取评价信息失败: ' + response.msg);  // 错误处理
                }
            } catch (error) {
                this.$message.error('获取评价信息失败');  // 异常处理
            }
        },
            /** 查询订单管理列表 */
            getList() {
                this.loading = true;
                listOrder(this.queryParams).then(response => {
                    this.orderList = response.rows;
                    this.total = response.total;
                    this.loading = false;
                });
            },
            // 取消按钮
            cancel() {
                this.open = false;
                this.reset();
            },
            // 表单重置
            reset() {
                this.form = {
                        orderId: null,
                        orderNum: null,
                        userId: null,
                        driverId: null,
                        tripTypeId: null,
                        orderType: null,
                        couponId: null,
                        tipNumber: null,
                        orderInfoId: null,
                        status: "0",
                        delFlag: null,
                        createBy: null,
                        createTime: null,
                        updateBy: null,
                        updateTime: null,
                        remark: null
            };
                this.resetForm("form");
            },
            /** 搜索按钮操作 */
            handleQuery() {
                this.queryParams.pageNum = 1;
                this.getList();
            },
            /** 重置按钮操作 */
            resetQuery() {
                this.resetForm("queryForm");
                this.handleQuery();
            },
            // 多选框选中数据
            handleSelectionChange(selection) {
                this.ids = selection.map(item => item.orderId)
                this.single = selection.length!==1
                this.multiple = !selection.length
            },
            /** 新增按钮操作 */
            handleAdd() {
                this.reset();
                this.open = true;
                this.title = "添加订单管理";
            },
            /** 修改按钮操作 */
            handleUpdate(row) {
                this.reset();
                const orderId = row.orderId || this.ids
                getOrder(orderId).then(response => {
                    this.form = response.data;
                    this.open = true;
                    this.title = "修改订单管理";
                });
            },
            /** 提交按钮 */
            submitForm() {
                this.$refs["form"].validate(valid => {
                    if (valid) {
                        if (this.form.orderId != null) {
                            updateOrder(this.form).then(response => {
                                this.$modal.msgSuccess("修改成功");
                                this.open = false;
                                this.getList();
                            });
                        } else {
                            addOrder(this.form).then(response => {
                                this.$modal.msgSuccess("新增成功");
                                this.open = false;
                                this.getList();
                            });
                        }
                    }
                });
            },
            /** 删除按钮操作 */
            handleDelete(row) {
                const orderIds = row.orderId || this.ids;
                this.$modal.confirm('是否确认删除订单管理编号为"' + orderIds + '"的数据项？').then(function() {
                    return delOrder(orderIds);
                }).then(() => {
                    this.getList();
                    this.$modal.msgSuccess("删除成功");
                }).catch(() => {});
            },
    /** 导出按钮操作 */
    handleExport() {
        this.download('order/order/export', {
            ...this.queryParams
        }, `订单管理.xlsx`)
    },
    // ======================  导入相关方法 start ===================
    /** 导入按钮操作 */
    handleImport() {
        this.upload.title = "订单管理导入";
        this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
        this.download('order/order/importTemplate', {
        }, `订单管理导入模板.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
        this.getList();
    },
    // 提交上传文件
    submitFileForm() {
        this.$refs.upload.submit();
    },
    // ======================  导入相关方法 end ===================
        }
    }
</script>

